﻿using System;
using System.Collections.Generic;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Core.Interfaces;

namespace VideoSeller.Business.Models
{
	public class OnlineRatingModel : Repository<OnlineRating>
	{
		private readonly IDatabaseSettingsProvider _databaseSettingsProvider;

		public OnlineRatingModel(IDatabaseSettingsProvider databaseSettingsProvider)
		{
			_databaseSettingsProvider = databaseSettingsProvider;
		}

		public int GetRate(int onlineContentId, bool positive)
		{
            if (positive)
            {
                int i = Math.Abs(Table.Where(x => x.OnlineContentId == onlineContentId).Sum(x => x.Like));
                return i;
            }
			return Math.Abs(Table.Where(x => x.OnlineContentId == onlineContentId).Sum(x => x.Unlike));
		}

		public int Rate(Guid userId, int onlineContentId, bool positive, string comment)
		{
           OnlineRating rating = Table.Where(m => m.OnlineContentId == onlineContentId && m.UserId == userId).FirstOrDefault();
           if (rating == null)
            {
                var ratingStep = _databaseSettingsProvider.RatingStep;

                rating = new OnlineRating
                    {
                        UserId = userId,
                        OnlineContentId = onlineContentId,
                        Comment = comment,
                        CreateTime = DateTime.Now,
                        Like = positive ? (short)ratingStep : (short)0,
                        Unlike = positive ? (short)0 : (short)ratingStep
                    };

                Insert(rating);
            }
			return GetRate(onlineContentId, positive);
		}

		public void DeleteAll(IEnumerable<OnlineRating> items)
		{
			foreach (var item in items)
			{
				var oncat = Table.SingleOrDefault(x => x.Id == item.Id);

				if (oncat != null)
				{
					Table.DeleteOnSubmit(oncat);
				}
			}

			SubmitAllChanges();
		}
	}
}